package capstone.tagit;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.widget.Toast;

import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;


public class TagsList extends ItemizedOverlay<Tag>
{
	private LinkedList<Tag> mOverlays = new LinkedList<Tag>();
	private LinkedList<Tag> mOverlaysBackup = new LinkedList<Tag>();
	private LinkedList<TagType> tagsOut = new LinkedList<TagType>();
	private Context mContext;
	Comparator<Tag> compare;
	public TagsList(Drawable defaultMarker, Context context)
	{
		super(boundCenterBottom(defaultMarker));
		compare = new TagComparator();
		mContext = context;
		populate();
	}
	public boolean addOverlay(Tag overlay)
	{
		boolean rVal = addTagToList(mOverlaysBackup,overlay);
		if (!tagsOut.contains(overlay.getType())){
			mOverlays.add(overlay);
		}
		populate();
		return rVal;
	}
	
	public void filterOutType(TagType type){
		if (!tagsOut.contains(type)){
			tagsOut.add(type);
		}
	}
	public void filterInType(TagType type){
		if (tagsOut.contains(type)){
			tagsOut.remove(type);
		}
	}


	public void filterList(){
		mOverlays = new LinkedList<Tag>();
		for (Tag check : mOverlaysBackup){
			if (!tagsOut.contains(check.getType())){
				mOverlays.add(check);
			}
		}
		populate();
	}
	
	@Override
	protected Tag createItem(int i)
	{
		try{
		return mOverlays.get(i);
		}catch(IndexOutOfBoundsException e){
			return null;
		}
	}

	@Override
	public int size()
	{
		return mOverlays.size();
	}
	@Override
	protected boolean onTap(int index)
	{
		if (mOverlays.isEmpty()){
			return false;
		}
		Tag item = mOverlays.get(index);
		Toast.makeText(mContext,
				item.getTitle()+"\n"+ item.getSnippet() + "\n" + item.getDate().toString(),
				Toast.LENGTH_SHORT).show();
		return true;
	}
	@Override
	public boolean onTouchEvent(android.view.MotionEvent event,
                            MapView mapView){
		if (mOverlays.isEmpty()){
			return false;
		}
		else{
			return super.onTouchEvent(event, mapView);
		}
	}
	
	private boolean addTagToList(List<Tag> list, Tag tag){
		ListIterator<Tag> listIter = list.listIterator();
		while(listIter.hasNext()){
			int comp = compare.compare(listIter.next(),tag);
			if (comp < 0){
				continue;
			}
			else if (comp == 0){
				return false;
			}
			else{
				listIter.previous();
				listIter.add(tag);
				return true;
			}
		}
		listIter.add(tag);
		return true;
	}
}